<?php
/**
 * 织梦付费可见插件
 * Created by PhpStorm.
 * User: 六久阁 www.lol9.cn
 * Date: 2018年06月30日
 * Time: 16:20:45
 */
$ver='2.0';
session_cache_limiter('private,must-revalidate');
require_once(dirname(__FILE__)."/config.php");
plugUpdateCheck();
editTemplate();
$protocol = getHttpProtocol();
$row = $dsql->GetOne("SELECT id FROM `#@__payment` WHERE code = 'xorpay' ");
if(empty($row)){
    ShowMsg("请先安装《织梦个人支付插件（Xorpay）》并填写配置信息！","http://www.lol9.cn/dedecj/2039.html");
    exit();
}
if(!file_exists(DEDEDATA.'/payment/xorpay.php')){
    $row = $dsql->GetOne("SELECT id FROM `#@__payment` WHERE code = 'xorpay' ");
    ShowMsg("请先填写Xorpay配置信息！", "sys_payment.php?dopost=install&pid={$row['id']}&pm=edit");
    exit();
}

require_once DEDEDATA.'/payment/xorpay.php';

if(empty($dopost)) $dopost = "";
$configfile = DEDEDATA.'/config.cache.inc.php';
//保存配置的改动


$configfile = DEDEDATA.'/config.cache.inc.php';
//更新配置函数
function ReWriteConfig()
{
    global $dsql,$configfile;
    if(!is_writeable($configfile))
    {
        echo "配置文件'{$configfile}'不支持写入，无法修改系统配置参数！";
        exit();
    }
    $fp = fopen($configfile,'w');
    flock($fp,3);
    fwrite($fp,"<"."?php\r\n");
    $dsql->SetQuery("SELECT `varname`,`type`,`value`,`groupid` FROM `#@__sysconfig` ORDER BY aid ASC ");
    $dsql->Execute();
    while($row = $dsql->GetArray())
    {
        if($row['type']=='number')
        {
            if($row['value']=='') $row['value'] = 0;
            fwrite($fp,"\${$row['varname']} = ".$row['value'].";\r\n");
        }
        else
        {
            fwrite($fp,"\${$row['varname']} = '".str_replace("'",'',$row['value'])."';\r\n");
        }
    }
    fwrite($fp,"?".">");
    fclose($fp);
}
function getRandString()
{
    $str = strtoupper(md5(uniqid(md5(microtime(true)),true)));
    return substr($str,0,8).'-'.substr($str,8,4).'-'.substr($str,12,4).'-'.substr($str,16,4).'-'.substr($str,20);
}
function getHttpProtocol() {
	$protocol = 'http';
    if ( !empty($_SERVER['HTTPS']) && strtolower($_SERVER['HTTPS']) !== 'off') {
        $protocol='https';
    } elseif ( isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] === 'https' ) {
        $protocol='https';
    } elseif ( !empty($_SERVER['HTTP_FRONT_END_HTTPS']) && strtolower($_SERVER['HTTP_FRONT_END_HTTPS']) !== 'off') {
        $protocol='https';
    }
    return $protocol;
}
function setCache()
{
    global $cfg_version,$ver;
    $first_use = false;
    $use_time = date('Y-m-d');
    $txt = DEDEDATA.'/module/liujiuge_hidden.txt';
    if(!file_exists($txt))
    {
        $id = getRandString();
        $first_use = true;
        $fp = fopen($txt,'w');
        $tData['id'] = $id;
        $tData['time'] = $use_time;
        $tData['ver'] = $ver;
        fwrite($fp,serialize($tData));
        fclose($fp);
    }else{
        $fp = fopen($txt,'r');
        $content = fread($fp, filesize($txt));
        fclose($fp);
        $content = unserialize($content);
        $id = $content['id'];
        $use_time = $content['time'];
        $tData['id'] = $id;
        $tData['time'] = date('Y-m-d');
        $tData['ver'] = $ver;
        $fp = fopen($txt,'w');
        fwrite($fp,serialize($tData));
        fclose($fp);
    }
    
}
function plugUpdateCheck()
{
    global $dsql,$cfg_db_language,$cfg_dbprefix;
    $txt = DEDEDATA.'/module/xorpay.txt';

    $isTableExist = $dsql->IsTable("#@__hiddens");
    if(!$isTableExist){
        $dsql->ExecuteSafeQuery("CREATE TABLE `{$cfg_dbprefix}hiddens` (
`id` int(10) unsigned NOT NULL auto_increment,
`aid` int(10) unsigned default '0' COMMENT '文章id',
`arcrank` smallint(6) default '0' COMMENT '阅读权限',
`price` decimal(10,2) unsigned default '0.00',
`body` text,
`created_at` datetime default NULL,
`updated_at` timestamp NULL default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP,
PRIMARY KEY  (`id`),
UNIQUE KEY `aid` (`aid`)
) ENGINE=MyISAM DEFAULT CHARSET={$cfg_db_language}");
    }
}
function editTemplate(){
    $path = dirname(__FILE__);
    $article_add_content = file_get_contents($path.'/templets/article_add.htm');
    if(strstr($article_add_content,'insertHidden')===false){
        $article_add_content = str_replace('#p#分页标题#e# </font>)','#p#分页标题#e# </font>)
                <div style="display: inline;">
                    <a id="insertHidden" href="javascript:;" style="padding:10px 10px;line-height: 20px;text-align: center;vertical-align: middle;color: #fff;border-radius: 5px;background: #D75847;text-decoration: none;"><span style="font-size: 14px;">设置隐藏内容</span></a>
                </div>',$article_add_content);
        $article_add_content = $article_add_content.'            <script src="https://cdn.bootcss.com/jquery/2.2.4/jquery.min.js"></script>
            <script src="https://cdn.bootcss.com/layer/3.1.0/layer.js"></script>
            <script>
              $(function () {
                  $("#insertHidden").click(function () {
                      layer.open({
                          type: 2,
                          title: \'填写隐藏内容\',
                          shadeClose: true,
                          shade: [0.3, \'#000\'],
                          maxmin: false, //开启最大化最小化按钮
                          area: [\'60%\', \'60%\'],
                          content: \'hidden_edit.php?aid=0\'
                      });
                  });
              });
          </script>';
        $fp = fopen($path.'/templets/article_add.htm','w');
        flock($fp,3);
        fwrite($fp,$article_add_content);
        fclose($fp);
    }
    $return_content = file_get_contents(DEDEROOT.'/plus/xorpay.php');
    if(strstr($return_content,'if(!isWeixin() && strlen($out_trade_no)==4)')===false){
        $return_content = str_replace('if($action==\'return\'):','if($action==\'return\'):
    if(!isWeixin() && strlen($out_trade_no)==4){
        echo "<script>top.layer.msg(\'支付成功！\',{icon: 1,time:1000},function() {
  top.location.reload()
});</script>";
        exit();
    }',$return_content);
        $fp = fopen(DEDEROOT.'/plus/xorpay.php','w');
        flock($fp,3);
        fwrite($fp,$return_content);
        fclose($fp);
    }
    $article_add_content = file_get_contents($path.'/templets/article_edit.htm');
    if(strstr($article_add_content,'insertHidden')===false){
        $article_add_content = str_replace('提取第一个图片为缩略图','提取第一个图片为缩略图
                <div style="display: inline;">
                    <a id="insertHidden" href="javascript:;" style="padding:10px 10px;line-height: 20px;text-align: center;vertical-align: middle;color: #fff;border-radius: 5px;background: #D75847;text-decoration: none;"><span style="font-size: 14px;">设置隐藏内容</span></a>
                </div>',$article_add_content);
        $article_add_content = $article_add_content.'            <script src="https://cdn.bootcss.com/jquery/2.2.4/jquery.min.js"></script>
            <script src="https://cdn.bootcss.com/layer/3.1.0/layer.js"></script>
            <script>
              $(function () {
                  $("#insertHidden").click(function () {
                      layer.open({
                          type: 2,
                          title: \'填写隐藏内容\',
                          shadeClose: true,
                          shade: [0.3, \'#000\'],
                          maxmin: false, //开启最大化最小化按钮
                          area: [\'60%\', \'60%\'],
                          content: \'hidden_edit.php?aid=<?php echo $arcRow["id"]?>\'
                      });
                  });
              });
          </script>';
        $fp = fopen($path.'/templets/article_edit.htm','w');
        flock($fp,3);
        fwrite($fp,$article_add_content);
        fclose($fp);
    }
}
if($dopost=="save")
{
    $info = $_POST['info'];
    $data = $_POST['basic'];
    foreach($data as $k=>$v)
    {
        $row = $dsql->GetOne("SELECT varname FROM `#@__sysconfig` WHERE varname LIKE '$k' ");
        if(is_array($row))
        {
            //存在就更新
            $dsql->ExecuteNoneQuery("UPDATE `#@__sysconfig` SET `value`='$v' WHERE varname='$k' ");
        }else{
            $row = $dsql->GetOne("SELECT aid FROM `#@__sysconfig` ORDER BY aid DESC ");
            $aid = $row['aid'] + 1;
            $inquery = "INSERT INTO `#@__sysconfig`(`aid`,`varname`,`info`,`value`,`type`,`groupid`)
VALUES ('$aid','$k','{$info[$k]}','$v','string','8')";
            $rs = $dsql->ExecuteNoneQuery($inquery);
            if(!$rs)
            {
                ShowMsg("有非法字符！");
                exit();
            }
            if(!is_writeable($configfile))
            {
                ShowMsg("成功保存，但由于 $configfile 无法写入，因此不能更新配置文件！");
                exit();
            }
        }

    }
    ReWriteConfig();
    //在模板中增加标记
    ShowMsg("成功更改配置！", "hidden.php");
    exit();
}
$protocol = getHttpProtocol();

$dsql->SetQuery("Select * From `#@__sysconfig` where groupid = 8 order by aid asc");
$dsql->Execute();
$i = 1;
$data = array();
while($row = $dsql->GetArray()) {
    $data[$row['varname']] = $row['value'];
    $i++;
}
$data['hidden_orderno'] = $data['hidden_orderno'] ? intval($data['hidden_orderno']) : 1;
$data['hidden_tip'] = $data['hidden_tip'] ? $data['hidden_tip'] : '提示: 该内容为付费隐藏内容，需要支付 <b>￥[money]元</b> 才能浏览。';

include DedeInclude('templets/hidden.htm');
setCache();

